package net.csiit.platform.codeguard.maven.plugin;

import net.csiit.platform.codeguard.tools.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.util.List;
import java.util.jar.JarFile;

/**
 * code encrypt maven compile plugin
 */
@Mojo(name = "codeGuard", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true)
public class CodeGuarderMojo extends AbstractGuardPackageMojo {

    /**
     * encrypt key
     */
    @Parameter(defaultValue = "${codeGuard.key}")
    private String key;
    @Parameter(defaultValue = "${codeGuard.jarFileName}")
    private String jarFileName;
    @Parameter(defaultValue = "${codeGuard.postfix}")
    private String postfix;
    @Parameter(defaultValue = "${codeGuard.encryptPackages}")
    private List<String> encryptPackages;

    public void execute() throws MojoExecutionException, MojoFailureException {
        if (StringUtils.length(key) != Constants.AES_KEY_LENGTH) {
            getLog().error("key must has 16 characters !");
            throw new MojoExecutionException("key must has 16 characters !");
        }

        try (JarFile jarFile = getJarFile(target, jarFileName)) {
            if (jarFile == null) {
                throw new MojoExecutionException("can not found target jar file : " + jarFileName);
            }

            getLog().info("[code-guard] begin to encrypt jar file : " + jarFile.getName());

            handleJarFile(jarFile, key, postfix, encryptPackages, true);

            getLog().info("[code-guard] encrypt jar file : " + jarFile.getName() + " complete !");
        } catch (MojoExecutionException e) {
            throw e;
        } catch (Exception e) {
            getLog().error(e);
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }

}
